package com.net.core.intercept;

import com.net.core.models.bean.User;
import com.net.core.core.YXException;
import com.net.core.models.user.service.UserService;
import com.net.core.utils.CurrentCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: zll
 * @Description: 安全拦截器
 * @DATE: 2020/11/17
 **/
@Slf4j
@Component
public class MustInterceptor implements HandlerInterceptor {

    @Resource
    CurrentCache currentCache;

    private static HashMap<String, User> userList = new HashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "86400");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return false;
        }
        response.setCharacterEncoding("UTF-8");

        String url = request.getRequestURL().toString();
        //无需登录就可访问的地址。
        if (UrlList.ableList(url)) {
            return true;
        }
        //获取token
        String token = request.getHeader("token");
        if (token == null || token.length() == 0) {
            throw new YXException("用户未登录");
        }
        User user = currentCache.getUser(token);
        if (user == null) {
            throw new YXException("无效token");
        }
        return true;
    }


    private boolean disableList(String userId, String url) throws IOException {
//        List<InterfaceObj> disableInterfaceList = userService.getDisableInterfaceList(organId);
//        for (InterfaceObj s : disableInterfaceList) {
//            if(url.contains(s.getRequestURL()))return true;
//        }
        if (false) {
            throw new YXException("权限不足");
        }
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        response.setCharacterEncoding("UTF-8");
    }

}
